package com.ideal.hadoopadmin.crontab.tool;

import com.ideal.hadoopadmin.crontab.db.ConnectionManager;
import com.ideal.hadoopadmin.crontab.property.Properties;
import com.ideal.tools.ssh.common.CommonProperties;
import com.ideal.tools.ssh.context.ClusterContext;
import com.ideal.tools.ssh.entity.LinuxMachine;

import java.io.*;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by CC on 2016/3/16.
 */
public class Tools {
    private static Logger logger = LoggerFactory.getLogger(Tools.class);
    /**
     * 获取hdfs名称
     * @return
     */
    public static String getHDFSInfoFileName(){
        String filename= Properties.HDFS_INFO_FILENAME+getCurrentDate()+".txt";
        return filename;
    }

    public  static  final  int DemoChangeDataBase = 0; //测试用1，正式换成 0
    public  static  final  int DemoEnvironmenttal = 0; //测试用1，正式换成 0

    /**
     * 获取kerbero 刷新结果 文件
     * @return
     */
    public static String getKerberosInfoFileName(){
        String filename=Properties.Kerberos_INFO_FILENAME+getCurrentDate()+".txt";
        return filename;
    }

    /**
     * 获取Linux prompt 更新文件
     * @return
     */
    public static String getLinuxPromptFileName(){
        String filename=Properties.Linux_Prompt_FileName+getCurrentDate()+".txt";
        return filename;
    }

    /**
     * 获取kerberos 刷新脚本 文件
     * @return
     */
    public static String getKerberosExeShellName(){
        String filename=Properties.Kerberos_EXE_FileName+getCurrentDate()+".sh";
        return filename;
    }

    public static String getKerberosCPShell(){
        String filename= Properties.Kerberos_CP_FileName+getCurrentDate()+".sh";
        return filename;
    }

    /**
     * 写入 linux 文件
     * @param path
     * @param sb
     */
    public static void writeLinuxFile(String path,StringBuffer sb){
        File file=new File(path);
        BufferedWriter writer=null;
        try {
            if(!file.exists()){
                file.createNewFile();
            }
            writer=new BufferedWriter(new FileWriter(file));
            writer.write(sb.toString());
            writer.flush();

//            for(String c:content){
//                writer.write(c);
//                writer.flush();
//            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (writer!=null){
                try {
                    writer.flush();
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 读取 txt 文件
     * @param path
     * @return
     */
    public static List<String> readFile2List(String path){
        List<String> txtList=new ArrayList<String>();

        File file=new File(path);

        if(!file.exists()){
            logger.info("Path["+path+"] is not exited!");
            return null;
        }

        BufferedReader reader=null;

        try {
            reader=new BufferedReader(new FileReader(file));

            String tmp="";

            while((tmp=reader.readLine())!=null){
//                logger.info(tmp);
                txtList.add(tmp);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(reader!=null)
                    reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return txtList;
    }


    /***
     * 批量执行 插入语句
     *
     * @param sqlList
     */
    public static void exeSQLBatch(List<String> sqlList) {
        Connection conn = ConnectionManager.getConnection();
        Statement stmt = null;
        try {
            conn.setAutoCommit(false);

            stmt = conn.createStatement();
            for (String sql : sqlList) {
                logger.info(sql);
                stmt.addBatch(sql);
            }
            stmt.executeBatch();

            //commit
            conn.commit();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            ConnectionManager.closeConn(conn);
        }
    }

    public static  void getCreateSqlParam(StringBuffer hql, String... str) {
        hql.setLength(0);
        for (String s : str) {
            hql.append(s);
        }
    }

    //测试用
    public static ClusterContext getDemoClusterContextDemo() {
//        Properties.initMySQL();//初始数据
        //构造测试ClusterContext  测试用
        Map<String, String> propertyMap = getAllParamByDB();;
        propertyMap.put(Properties.Kerberos_EXE_FileName, Properties.Kerberos_EXE_FileName); //kerberos脚本名
        propertyMap.put(Properties.Kerberos_INFO_FILENAME, Properties.Kerberos_INFO_FILENAME);
        CommonProperties commonProperties = new CommonProperties(propertyMap);
        ClusterContext context = new ClusterContext(commonProperties);
        //构造机器参数
        List<LinuxMachine> machineList = getAllMachineByDB();
        context.setOriginalList(machineList);
        //构造结束  测试用
        return context;
    }

    //解析时间
    public static String parseStringToDate(String start) {
        String time = "";
        SimpleDateFormat format=new SimpleDateFormat("MM/dd/yy HH:mm:ss");
        try {
            Date date = format.parse(start);
            time = String.valueOf(date.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return time;
    }

    //获取当前时分秒 格式：yyyyMMddHHmmss
    public static String getCurrentDate() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String date = format.format(System.currentTimeMillis());
        return date;
    }
    //获取当前时间
    public static String getCurrentDateTime() {
        long date = new Date().getTime();
        return String.valueOf(date);
    }

    //获取WebAppShellPath
    public static String getWebAppShellPath(){
        return  Properties.instance().getPropertyByKey(CommonProperties.WEBAPP_SHELL_PATH, "");
    }

    //获取WebInitPath
    public static String getWebInitPath(){
        return  Properties.instance().getPropertyByKey(CommonProperties.WEBAPP_INIT_PATH, "");
    }
    //获取getkerberosFileName
    public static String getkerberosFileName(){
        return getWebInitPath() + "/" + Properties.Kerberos_INFO_FILENAME + Tools.getCurrentDate() + ".txt";
    }

    public  static List<LinuxMachine>  getAllMachineByDB(){
        String sql= "SELECT cm.machineIp,cm.loginUserName,cm.loginPassWord,ct.machineTypeName FROM cluster_machine cm,cluster_machine_type ct where cm.machineTypeId= ct.machineTypeId";
        Connection conn=ConnectionManager.getConnection();
        List<Map<String, Object>> resHdfs = ConnectionManager.queryDB(conn, sql);
        List<LinuxMachine> machines = new ArrayList<LinuxMachine>();
        for(Map<String, Object>  machine : resHdfs){
            LinuxMachine newMachine = new LinuxMachine();
            newMachine.initIP(machine.get("MACHINEIP").toString());
            newMachine.initLoginName(machine.get("LOGINUSERNAME").toString());
            newMachine.initPassWord(machine.get("LOGINPASSWORD").toString());
            newMachine.initMachineType(LinuxMachine.MachineType.getEnumMachineType(machine.get("MACHINETYPENAME").toString()));
            machines.add(newMachine);
        }
        return machines;
    }

    public  static Map<String,String>  getAllParamByDB(){
        String sql= "SELECT parameterKey,parameterVal from cluster_parameter";
        Connection conn=ConnectionManager.getConnection();
        List<Map<String, Object>> resParams = ConnectionManager.queryDB(conn, sql);
        Map<String,String> params = new HashMap<String,String>();
        for(Map<String, Object>  param : resParams){
            params.put(param.get("PARAMETERKEY").toString(),param.get("PARAMETERVAL").toString());
        }
        return params;
    }

}
